
import 'dart:async';

import 'package:bookshelf/event/read_block_event.dart';
import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/serial/send_helper.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../entity/inventory_entity.dart';
import '../entity/setting_entity.dart';
import '../event/inventory_event.dart';
import '../log/logger.dart';
import '../main.dart';
import '../socket/send_helper.dart';
import '../widget/app_bar.dart';



class Up extends StatefulWidget {
  const Up({Key? key}) : super(key: key);

  @override
  State<Up> createState() => _UpState();
}

class _UpState extends State<Up> {

  final RxList<InventoryEntity> _inventoryList = RxList();
  final RxList<InventoryEntity> _filterList = RxList();
  var  _currentList = [];
  var total = 0.obs;
  List<SettingEntityPlace> ants = [];
  StreamSubscription? inventorySubscription;
  StreamSubscription? readBlockSubscription;

  int blockIndex = 0;
  // int inventoryIndex = 0;

  bool isFinish = false;

  final box = GetStorage('uid_no');

  RxBool checkBox = RxBool(false);
  RxBool showState = RxBool(false);

  @override
  initState() {
    super.initState();

    if(settingEntity.place != null){
      for (var element in settingEntity.place!) {
        if(element.state == 0){
          ants.add((element));
        }

      }
    }

    //盘点回调
    inventorySubscription = eventFactory.on<InventoryEvent>().listen((event) {

      for (var element in event.data) {
        try{
          var entity = InventoryEntity()
            ..uid = element
            ..ant = event.ant
            ..currentPlace = settingEntity.place!.firstWhere((e) => (e.ant!.padLeft(2,'0') == event.ant.padLeft(2,'0'))).place;
          entity.currentPlaceName = _analyzePlace(entity.currentPlace);
          _inventoryList.add(entity);
          if(!_currentList.contains(entity.uid)){
            _filterList.add(entity);
          }
          total.value = checkBox.value?_filterList.length:_inventoryList.length;
        }catch(e){
          Logger().write('uid = $element,ant = ${event.ant}, error =  $e \r\n');
        }
      }
      ants.removeWhere((element) => element.ant == event.ant);
      print('ants=$ants');
      if(ants.isEmpty){
        BotToast.closeAllLoading();
        _startReadBlock();
      }
    });

    //读块回调
    readBlockSubscription = eventFactory.on<ReadBlockEvent>().listen((event) {
      print('ReadBlockEvent ${event.no}');
      _setBlock(event.no);
    });

    _queryBook();

  }

  // _send() async {
  //   var data = await inventoryWithAnt(ants.map((e) => e.ant!).toList());
  //   hfSerialPortHelper.sendData(data);
  // }

  _queryBook() async {
    BotToast.showLoading(clickClose: true);
    var list = await findRfidList();
    if(list != null){
      _currentList = list.map((e) => e.rfid).toList();
    }
    var data = await inventoryWithAnt(ants.map((e) => e.ant!).toList());
    hfSerialPortHelper.sendData(data);
  }

  // //开始盘点
  // _inventory(){
  //   if(readers.isNotEmpty ){
  //     if(inventoryIndex<readers.length){
  //       hfSerialPortHelper.sendData(inventoryWithAnt(ants.map((e) => e.ant!).toList()));
  //     }else{
  //       BotToast.closeAllLoading();
  //       _startReadBlock();
  //     }
  //   }
  // }

  String str = '';

  //开始读块
  _startReadBlock() async {
    if(blockIndex<_inventoryList.length){
      var item = _inventoryList[blockIndex];
      if(item.uid != null && box.hasData(item.uid!)){
        _setBlock(box.read(item.uid!));
      }else{
        var data = await readBlocksWithAnt(item.uid!, item.ant!);
        hfSerialPortHelper.sendData(data);
      }
    }else{
      isFinish = true;
    }
  }

  _setBlock(no){
    var item =  _inventoryList[blockIndex];
    _inventoryList.removeAt(blockIndex);
    item.no = no??'';
    _inventoryList.insert(blockIndex, item);
    var element = _filterList.firstWhereOrNull((element) => element.uid == item.uid);
    if(element != null){
      var index = _filterList.indexOf(element);
      _filterList.removeAt(index);
      _filterList.insert(index,item);
    }

    if(item.uid != null && item.no != null && item.no != ''){
      str += '${item.uid!}=${item.no},';
      box.write(item.uid!, item.no);
    }
    blockIndex++;
    _startReadBlock();
  }

  @override
  void dispose() {
    inventorySubscription?.cancel();
    inventorySubscription = null;
    readBlockSubscription?.cancel();
    readBlockSubscription = null;
    super.dispose();
  }


  _title(){
    return Container(
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              // if(!isFinish){
              //   toastWarn('还未盘点完成。。。。');
              //   return;
              // }
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:40.w,fit: BoxFit.fitWidth,),
          ),
          Text("上架清单",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
          Obx(() => Text("总量:${total.value}",style: TextStyle(color: const Color.fromRGBO(51, 226, 255, 1),fontSize: 8.sp),))
        ],
      )
    );
  }

  _divider(){
    return Divider(
      height: 0.5.h,
      indent: 4.w,
      endIndent: 4.w,
      color: const Color.fromRGBO(56, 141, 255, 1),
    );
  }

  _listLabel(){
    return Container(
      padding: EdgeInsets.only(top: 5.h,bottom: 5.h),
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _label('UID',90.w,),
          _label('图书条码号',90.w),
          _label('当前位置',125.w),
          _label('状态',50.w),
        ],
      )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: const Color.fromRGBO(55, 112, 173, 1),fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _item(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: color,fontSize: 6.sp),textAlign: TextAlign.center,),
    );
  }


  _itemBuilder(index){
    var item = checkBox.value?_filterList[index]:_inventoryList[index];
    return Container(
      padding: EdgeInsets.only(top: 5.h,bottom: 5.h),
      alignment: Alignment.center,
      child: Row(
        children: [
          _item('${item.uid}',90.w),
          _item(item.no==null?'':item.no!.isEmpty?'解析失败':item.no,90.w),
          // _item('${item.initPlace}',85.w),
          _item('${item.currentPlaceName}',125.w),
          Obx(() => _item(showState.value?item.state??'':'',50.w, color: item.state == '上架成功'?const Color.fromRGBO(56, 141, 255, 1):const Color.fromRGBO(252, 130, 91, 1))),
        ],
      )
    );
  }

  _analyzePlace(String? place){
    if(place == null){
      return null;
    }
    // String room = place.substring(0,2);
    // String column = place.substring(2,6);
    String side = place.substring(6,8);
    String knot = place.substring(8,10);
    String floor = place.substring(10,12);
    return '${settingEntity.roomName}${settingEntity.columnNo}列${side=='01'?'A面':'B面'}$knot节$floor层';
  }

  _filter(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Obx(() => Checkbox(
          value: checkBox.value,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          onChanged: (data) {
            checkBox.value = !checkBox.value;
            total.value = checkBox.value?_filterList.length:_inventoryList.length;
          },
        )),
        Text("仅显示未上架     ",style: TextStyle(color: Colors.black,fontSize: 6.sp),),
      ],
    );
  }

  _booksContainer(){
    return Container(
      margin: EdgeInsets.only(left: 8.w,right: 8.w,top: 10.h),
      width: double.infinity,
      height: 610.h,
      decoration: const BoxDecoration(
        color: Colors.white
      ),
      child: Column(
        children: [
          _filter(),
          _listLabel(),
          _divider(),
          SizedBox(
            height: 520.h,
            child: Obx(() => ListView.separated(
              itemBuilder: (context, index) {
                return _itemBuilder(index);
              },
              itemCount: checkBox.value?_filterList.length:_inventoryList.length,
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  height: 0.5.h, // Divider 组件高度
                  // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
                  indent: 4.w, // 分割线左侧间距
                  endIndent: 4.w, // 分割线右侧间距
                  color: Colors.grey,
                );
              },
            ),),
          ),
          SizedBox(height: 10.h,),
          InkWell(
            onTap: () async {
              if(showState.value){
                return;
              }
              if(!isFinish){
                toastWarn('还未盘点完成。。。。');
                return;
              }
              if(_filterList.isEmpty){
                toastWarn('无未上架读书。。。');
                return;
              }
              sendLog(_filterList.toString());

              var list  = [];
              BotToast.showLoading();
              for (var element in _filterList) {
                if(element.no!.isEmpty){
                  element.state = '上架失败';
                  continue;
                }

                var book =  await findBook(element.no,element.uid,element.currentPlace);
                if(book != null){
                  // book.rfid = element.uid;
                  // book.place = element.currentPlace;
                  if(book.no != element.no){
                    sendLog('sip2请求条码号不一致 请求参数: no = ${element.no} uid = ${element.uid} 返回参数: no = ${book.no}',);
                    element.state = '上架失败';
                  }else{
                    list.add(book.toJson());
                    element.state = '上架成功';
                  }
                }else{
                  element.state = '上架失败';
                }

              }
              BotToast.closeAllLoading();
              var result = await init(list);

              if(result){
                for (var element in _inventoryList) {
                  element.state ??= '上架成功';
                }
                showState.value = true;
              }
            },
            child:  Image.asset("assets/images/confirm_up.png", width:70.w, fit: BoxFit.fitWidth,),
          ),
        ],
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(),
            _title(),
            _booksContainer(),
          ],
        ),
      ),
    );
  }
}

